package com.invest.task.jsl;

import com.invest.common.constant.BusinessConstants;
import com.invest.common.utils.DateUtils;
import com.invest.common.utils.StringUtils;
import com.invest.domain.entity.CbData;
import com.invest.mapper.CbDataMapper;
import com.invest.mapper.RiskFreeMapper;
import com.invest.utils.CbDataUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



/**
 * @projectName: invest
 * @author: yuch
 * @description: TODO
 * @date: 2025/1/15 16:24
 */


@Component
@Slf4j
public class CbDatail {
    @Autowired
    private CbDataMapper cbDataMapper;

    @Autowired
    private RiskFreeMapper riskFreeMapper;

    public static Double riskfree;

    String baseurl = "https://www.jisilu.cn/data/convert_bond_detail/";


    public void start() throws IOException {
        log.info("------------开始获取可转债详情信息----------------");
        List<CbData> cbDataList = cbDataMapper.selectAll();
        log.info("系统可转债数量为：{}", cbDataList.size());
        for (CbData cbData : cbDataList) {
            this.updateDetail(cbData);
        }
    }

    public void updateDetail(CbData cbData) throws IOException {
        if (riskfree == null) {
            String latestRate = riskFreeMapper.getLatestRate();
            riskfree = Double.parseDouble(latestRate);
        }
        String bondId = cbData.getBondId();
        String id = cbData.getId();
        String price = cbData.getPrice();
        CbData newCbData = new CbData();
        Document document = Jsoup.connect(baseurl + bondId).get();
        if (document.html().contains("不存在")) {
            return;
        }
        Elements infoData = document.getElementsByClass("info_data");//可转债数据
        Element element = infoData.get(0);
        Elements tables = element.getElementsByClass("jisilu_tcdata");//可转债表格数据
        Element table1 = tables.get(0);
        Element table2 = tables.get(1);
        Element table3 = tables.get(2);
        Element bondNmDiv = table1.select("div.bond_nm").first();
        String ownText = bondNmDiv.ownText().trim();
        log.info("可转债id===>"+ownText);
         if (StringUtils.isEmpty(ownText) || !ownText.equals(bondId)) {
            return;
        }
        Element industryNew = table1.getElementById("industry_new");
         Element redeem_price = table1.getElementById("redeem_price");
        String redeemPri = redeem_price.text();
        String[] split12 = redeemPri.split("\\+");
        redeemPri = split12[0];
        Element convert_dt = table1.getElementById("convert_dt");
        // table3
        Element cpn_desc = table3.getElementById("cpn_desc");
        String text = cpn_desc.text();
         ArrayList<String> list = new ArrayList<>();
        String[] split = text.replace("，", ",").replace("、", ",").split(",");
        for (String s : split) {
            String trim = getrate(s).trim();
             list.add(trim);

        }

        //计算剩余年限
        if(StringUtils.isEmpty(cbData.getYearLeft())||BusinessConstants.NULL_DATA.equals(cbData.getYearLeft())){
            newCbData.setYearLeft(DateUtils.yearLeft(cbData.getMaturityDt()));
            cbData.setYearLeft(DateUtils.yearLeft(cbData.getMaturityDt()));
        }
        String bondValue = CbDataUtil.getpureBondPrice(list, redeemPri, cbData.getYearLeft().toString(),riskfree);

        Element nextPutDt = table1.getElementById("next_put_dt");

        Element put_price = table1.getElementById("put_price");
         String text1 = put_price.text();
        String[] split1 = text1.split("\\+");
        if (!StringUtils.isEmpty(nextPutDt.text()) && !"-".equals(nextPutDt.text().trim())) {

            String backBondYield =  CbDataUtil.getBackBondYield(price.toString(), split1[0], list.get(list.size() - 2), nextPutDt.text());
//            if (!StringUtils.isEmpty(cbData.getRedeemDt())) {
//                //回售日期为空，说明没有回售条款
//                backBondYield ="-";
//            }
            newCbData.setPutYtmRt(String.format("%.2f", Double.parseDouble(backBondYield)));
        }

        newCbData.setId(id);
        newCbData.setIndustryNew(industryNew.text());
        newCbData.setRedeemPrice(redeemPri);
        newCbData.setCpnDesc(cpn_desc.text());
        newCbData.setBondValue(String.format("%.2f", Double.parseDouble(bondValue)));
        newCbData.setNextPutDt(nextPutDt.text());
        newCbData.setPutPrice(put_price.text());
        newCbData.setProfitUpdateTime(new Date());
        newCbData.setConvertDt(convert_dt.text());//转股起始日

        cbDataMapper.updateCbData(newCbData);
    }







    private String getrate(String rate) {
        // 正则表达式，用于匹配数字（包括小数点）
        String regex = "\\d+(\\.\\d+)?";

        // 编译正则表达式
        Pattern pattern = Pattern.compile(regex);

        // 创建Matcher对象
        Matcher matcher = pattern.matcher(rate);

        // 查找匹配的子字符串
        if (matcher.find()) {
            // 获取匹配的结果
            String number = matcher.group();
            return number;
        }
        return "";
    }
}
